package sau.diyizu.media.music;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import sau.diyizu.media.ItemListener;
import sau.diyizu.media.R;
import sau.diyizu.media.bean.Music;

import java.util.List;

/**
 @author JYD
 @version 1.0
 @since 2020/12/15 0:20 */
public class MusicsAdapter extends RecyclerView.Adapter<MusicsAdapter.VH> {
    public static final int TYPE_LONG_CLICK = 1;

    private LayoutInflater inflater;
    private List<Music> musicList;
    private ItemListener listener = ItemListener.DEFAULT_NULL_INSTANCE;

    public List<Music> getMusicList() {
        return musicList;
    }

    public void setDataAndNotify(List<Music> musicList) {
        this.musicList = musicList;
        notifyDataSetChanged();
    }

    @Override
    public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        inflater = LayoutInflater.from(recyclerView.getContext());
    }

    @NonNull
    @Override
    public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        VH vh = new VH(inflater.inflate(R.layout.item_music, parent, false));
        vh.itemView.setOnClickListener(v -> listener.onTrigger(vh));
        vh.itemView.setOnLongClickListener(v -> {
            listener.onTrigger(vh, TYPE_LONG_CLICK);
            return true;
        });
        return vh;
    }

    @Override
    public void onBindViewHolder(@NonNull VH holder, int position) {
        Music music = musicList.get(position);
        holder.name_tv.setText(music.name);
        holder.duration_tv.setText(music.formatDuration());
    }

    @Override
    public int getItemCount() { return musicList != null ? musicList.size() : 0; }

    public void setItemListener(ItemListener itemListener) {
        this.listener = itemListener;
    }

    static class VH extends RecyclerView.ViewHolder {
        TextView name_tv;
        TextView duration_tv;

        public VH(@NonNull View itemView) {
            super(itemView);
            name_tv = itemView.findViewById(R.id.name_tv);
            duration_tv = itemView.findViewById(R.id.duration_tv);
        }
    }
}
